package JUC_Advanced.chapter1_CompletableFuture;

import java.util.concurrent.*;

/**
 * @Author: GuSongLiao
 * @Date: 2024/3/6 16:12
 * @Description: completablefuture 实战
 */
public class CompletableFutureUseDemo {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newFixedThreadPool(3);

        CompletableFuture.supplyAsync(() -> {
            System.out.println(Thread.currentThread().getName());
            try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            int i = ThreadLocalRandom.current().nextInt(10);
            if (i % 2 == 0) {
                i = 10 / 0;
            }
            return i;
        }, executorService).whenComplete((v, e) -> { // v : 上一步的值，e: 异常信息
            // 通常需要判断 e == null 后执行业务
            System.out.println("whenComplete: " + v);
        }).exceptionally(e -> {
            e.printStackTrace();
            System.out.println("exceptionally: " + e.getCause() + " " + e.getMessage());
            return null;
        });

        System.out.println("main end");

        //主线程不要立刻关闭，否则 CompletableFuture 默认使用的线程池会立刻关闭，暂停3秒线程   或者不适用延迟的代码 使用自己的线程池
//        try {
//            TimeUnit.SECONDS.sleep(3);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
    }
}
